<script setup lang="ts">
  import { ref } from 'vue'
  import _ from 'lodash'
  import {
    useGetOrderFinishTemplateOptions,
    useGetOrderFinishTemplateOptionsById,
    useSaveOrderFinishTemplate,
  } from './services/index'
  import { ElMessage, FormInstance } from 'element-plus'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'

  const props = defineProps({
    modalTitle: {
      type: String,
      default: () => '关联结单模版',
    },
    orderModuleId: String,
  })

  const emits = defineEmits<{
    (e: 'updated'): void
  }>()

  // 表单验证规则
  const rules = ref({
    workStatementTemplateIds: [
      { required: true, message: '请选择模版', trigger: ['change', 'blur'] },
    ],
  })

  // 使用获取结单模版下拉选项服务
  const {
    loading: getOrderFinishTemplateOptionsLoading,
    options: orderFinishTemplateOptions,
    getOptionsFn: getOrderFinishTemplateOptionsFn,
  } = useGetOrderFinishTemplateOptions

  // 使用根据模块id获取关联结单模版服务
  const {
    loading: getOrderFinishTemplatesByIdLoading,
    list: orderFinishTemplates,
    getListFn: getOrderFinishTemplatesByIdFn,
  } = useGetOrderFinishTemplateOptionsById

  // 使用保存结单模版服务
  const { loading: saveOrderFinishTemplateLoaing, saveFn: saveOrderFinishTemplateFn } =
    useSaveOrderFinishTemplate

  // 弹窗的显示状态
  const visible = ref(false)

  // 表单
  const form = ref<{ workStatementTemplateIds: Array<string> }>({
    workStatementTemplateIds: [],
  })

  /**
   * 显示弹窗方法
   */
  const showModalFn = async () => {
    visible.value = true
    await getOrderFinishTemplateOptionsFn('')
    if (props.orderModuleId) {
      await getOrderFinishTemplatesByIdFn(props.orderModuleId)
      form.value.workStatementTemplateIds = orderFinishTemplates.value
    }
  }

  // 获取模版下拉选项关键字
  const getTemplateOptionsKeyword = ref('')

  /**
   * 获取模版下拉选项
   */
  const handleGetTemplateOptions = _.throttle((query: string) => {
    if (getTemplateOptionsKeyword.value !== query) {
      getTemplateOptionsKeyword.value = query
      getOrderFinishTemplateOptionsFn(getTemplateOptionsKeyword.value)
    }
  }, 500)

  // 表单组件实例
  const formRef = ref<FormInstance>()

  /**
   * 监听保存按钮点击
   */
  const onSaveBtnClick = async () => {
    if (formRef.value) {
      try {
        await formRef.value.validate()
        const res = await saveOrderFinishTemplateFn(
          props.orderModuleId,
          form.value.workStatementTemplateIds,
        )
        if (res.success) {
          emits('updated')
          visible.value = false
        } else {
          ElMessage({
            type: 'error',
            message: res.message,
          })
        }
      } catch (e) {
        /**
         * 校验不通过
         * 切不可删除catch，否则验证失败时会报错，加上catch就不会
         */
      }
    }
  }
</script>

<template>
  <div>
    <span @click="showModalFn">
      <slot></slot>
    </span>

    <HModal v-model="visible" :title="props.modalTitle" size="small">
      <el-form
        v-loading="getOrderFinishTemplatesByIdLoading || saveOrderFinishTemplateLoaing"
        :model="form"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item required prop="workStatementTemplateIds" label="关联结单模版">
          <el-select
            multiple
            clearable
            filterable
            placeholder="请选择"
            :filter-method="handleGetTemplateOptions"
            :loading="getOrderFinishTemplateOptionsLoading"
            v-model="form.workStatementTemplateIds"
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            reserve-keyword
          >
            <el-option
              v-for="option in orderFinishTemplateOptions"
              :key="option.id"
              :value="option.id"
              :label="option.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onSaveBtnClick">保存</HButton>
        <HButton is-modal @click="visible = false">关闭</HButton>
      </template>
    </HModal>
  </div>
</template>
